package com.example.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.example.common.mq.SeckillOrderTo;
import com.example.common.utils.R;
import com.example.common.vo.MemberResponseVo;
import com.example.gulimall.seckill.feign.CouponFeignService;
import com.example.gulimall.seckill.feign.ProductFeignService;
import com.example.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.example.gulimall.seckill.service.SecKillService;
import com.example.gulimall.seckill.to.SecKillRedisTo;
import com.example.gulimall.seckill.vo.SeckillSessionVo;
import com.example.gulimall.seckill.vo.SkuInfoVo;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
public class SecKillServiceImpl implements SecKillService {

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    RedissonClient redissionClient;

    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:skus";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    @Override
    public void uploadSeckillSkuLatest3Days() {
        //查看当前服务
        R last3Days = couponFeignService.getLast3Days();
        if(last3Days.getCode() == 0){
            List<SeckillSessionVo> data = last3Days.getData(new TypeReference<List<SeckillSessionVo>>() {});
            //缓存活动信息和商品信息分别到redis
            saveSessionInfos(data);
            saveSessionSkus(data);
        }
    }

    @Override
    public List<SecKillRedisTo> getCurrentSeckillSkus() {

        // 1.确定当前时间的秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        if(keys != null)
        for (String key : keys) {
            String timer = key.split(":")[2];
            String[] s = timer.split("_");
            Long start = Long.parseLong(s[0]);
            Long end = Long.parseLong(s[1]);
            if(time >= start && time <= end){
                //获取当前信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> objects = ops.multiGet(range);
                if(objects != null && objects.size() >= 0)
                return objects.stream().map(item -> JSON.parseObject(item.toString(), SecKillRedisTo.class)).collect(Collectors.toList());
            }
        }


        return null;
    }

    @Override
    public SecKillRedisTo getSkukillInfo(Long skuId) {

        // 1.找到所有需要参与秒杀的商品的key信息
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        Set<String> keys = ops.keys();
        if(keys != null && keys.size() > 0){
            String regx = "\\d_" + skuId.toString();
            for (String key : keys) {
                if(Pattern.matches(regx,key)){
                    String s = ops.get(key);
                    SecKillRedisTo secKillRedisTo = JSON.parseObject(s, SecKillRedisTo.class);
                    long time = new Date().getTime();
                    if(time >= secKillRedisTo.getStartTime() && time <= secKillRedisTo.getEndTime()){
                        return secKillRedisTo;
                    }else{
                        secKillRedisTo.setRandomCode("");
                        return secKillRedisTo;
                    }
                }
            }
        }
        return null;
    }

    @Override
    public String kill(String killId, String key, Integer num) throws InterruptedException {
        MemberResponseVo respVo = LoginUserInterceptor.loginUser.get();
        BoundHashOperations<String, String, String> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String s = ops.get(killId);
        if(StringUtils.isEmpty(s)){
            return null;
        }else{
            SecKillRedisTo to = JSON.parseObject(s, SecKillRedisTo.class);
            // 校验时间合法性
            long time = new Date().getTime();
            if(time < to.getStartTime() || time > to.getEndTime())
                return null;
            // 校验随机码和商品id
            if(to.getRandomCode().equals(key) && killId.equals(to.getPromotionId()+"_"+to.getSkuId())){
                // 验证购物数量是否合理
                if(to.getSeckillLimit() <= num){
                    // 判断当前用户是否已经买过
                    String userkey = respVo.getId() + "_" + to.getPromotionId() + "_" + to.getSkuId();
                    // 当秒杀解释自动清空
                    if(redisTemplate.opsForValue().setIfAbsent(userkey, num.toString(), to.getEndTime() - new Date().getTime(), TimeUnit.MICROSECONDS)){
                        //没买过
                        RSemaphore semaphore = redissionClient.getSemaphore(SKU_STOCK_SEMAPHORE + to.getRandomCode());
                        try{
                           semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                            // 快速下单给MQ发消息
                            String timeId = IdWorker.getTimeId();
                            SeckillOrderTo seckillOrderTo = new SeckillOrderTo();
                            seckillOrderTo.setOrderSn(timeId);
                            seckillOrderTo.setNum(num);
                            seckillOrderTo.setPromotionSessionId(to.getPromotionId());
                            seckillOrderTo.setSkuId(to.getSkuId());
                            seckillOrderTo.setSeckillPrice(to.getSeckillPrice());
                            seckillOrderTo.setMemberId(respVo.getId());
                            rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",seckillOrderTo);
                            return timeId;
                        }catch (InterruptedException e){
                            return null;
                        }
                    } else
                        return null;
                }else
                    return null;
            }else
                return null;
        }
    }

    private void saveSessionInfos(List<SeckillSessionVo> vo){
        if(vo == null)
            return;
        vo.stream().forEach(session->{
            Long startTime = session.getStartTime().getTime();
            Long endTime = session.getEndTime().getTime();
            String key = SESSIONS_CACHE_PREFIX + startTime + "_" + endTime;
            if(!redisTemplate.hasKey(key)){
                List<String> collect = session.getRelationSkus().stream().map(item->item.getPromotionId().toString()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                //缓存活动信息 检查是不是已经保存过了
                redisTemplate.opsForList().leftPushAll(key,collect);
            }
        });
    }

    //所有秒杀场的数据
    private void saveSessionSkus(List<SeckillSessionVo> vo){

        // 每一个场次信息不一样 所以redis前缀不一样
        vo.stream().forEach(session->{
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(secSkuvo->{
                String s = UUID.randomUUID().toString().replace("-", "");
                // 检测是否已经上架
                if(!ops.hasKey(secSkuvo.getPromotionId()+"_"+secSkuvo.getSkuId().toString())){
                    // 缓存商品
                    SecKillRedisTo to = new SecKillRedisTo();
                    // 1.Sku基本数据
                    R skuinfo = productFeignService.skuinfo(secSkuvo.getSkuId());
                    if(skuinfo.getCode() == 0){
                        SkuInfoVo skuInfo = skuinfo.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                        to.setSkuInfoVo(skuInfo);
                    }
                    // 2.SKu秒杀信息
                    BeanUtils.copyProperties(session,to);

                    // 时间信息
                    to.setStartTime(session.getStartTime().getTime());
                    to.setEndTime(session.getEndTime().getTime());

                    // 3.随机码 不知道随机码 防止秒杀被抢跑 顺便保护高并发 可以搞信号量
                    to.setRandomCode(s);
                    String json = JSON.toJSONString(to);
                    ops.put(secSkuvo.getPromotionId()+"_"+secSkuvo.getSkuId().toString(),json);
                    // 设置redis信号量 防止高并发访问数据库 崩
                    RSemaphore semaphore = redissionClient.getSemaphore(SKU_STOCK_SEMAPHORE + s);
                    semaphore.trySetPermits(secSkuvo.getSeckillCount().intValue());
                }


            });
        });
    }
}
